package com.priox.sigar.jsf.aop;

import com.priox.sigar.jsf.util.FindCrudBeanBase;
import com.priox.sigar.server.infrastructure.persistence.exception.ApplicationException;
import com.priox.sigar.util.TimeObserver;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.primefaces.context.RequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.faces.application.FacesMessage;

//@Aspect
//@Component("mapperAspect")
public class MapperAspect {
    protected final Logger logger = LoggerFactory.getLogger(getClass());

    private static final Logger SQLLOG = LoggerFactory.getLogger("sqlLog");

    @PostConstruct
    public void init() {

    }

    @Pointcut("bean(*Mapper)")
    private void mapper() {

    }

    @Pointcut("execution(public * *.*(..))")
    private void publicMethodSelectEvent() {
    }

    @Around("mapper()& publicMethodSelectEvent()  )")
    public Object logAllMethodsPainterAndTeacher(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        String method = proceedingJoinPoint.getSignature().toShortString();
        try {
            TimeObserver tio = new TimeObserver("executing method " + method);
            tio.empezar();
            logger.debug("Around: Before executing:" + method);
            Object obj = proceedingJoinPoint.proceed();
            logger.debug("Around: After executing:" + method);
            tio.terminar();
            SQLLOG.debug(tio.mostrarMsg());

            return obj;
        } catch (Throwable throwable) {
            logger.error("Problemas llamado al metodo: " + method, throwable);
            throwable.printStackTrace();
            Object target = proceedingJoinPoint.getTarget();
            if (target instanceof FindCrudBeanBase) {
                FindCrudBeanBase find = (FindCrudBeanBase) target;
                if (throwable instanceof ApplicationException) {
                    find.addMessage(throwable.getMessage(), FacesMessage.SEVERITY_FATAL, ((ApplicationException) throwable).getParameters());
                } else {
                    find.addMessage(throwable.getMessage(), FacesMessage.SEVERITY_FATAL, throwable);
                }

            }
            RequestContext context = RequestContext.getCurrentInstance();
            context.addCallbackParam("existError", true);
            return null;
        }
    }

}